import os
from models import User, Book, Admin
from database import Database
from utils import clear_screen, print_menu

class LibrarySystem:
    def __init__(self):
        self.db = Database()
        self.current_user = None

    def login(self):
        clear_screen()
        print("=== 图书管理系统登录 ===")
        username = input("请输入用户名: ")
        password = input("请输入密码: ")
        
        user = self.db.authenticate_user(username, password)
        if user:
            self.current_user = user
            print(f"欢迎回来, {user.username}!")
            return True
        else:
            print("用户名或密码错误!")
            return False

    def run(self):
        while True:
            if not self.current_user:
                if not self.login():
                    continue
            
            if isinstance(self.current_user, Admin):
                self.admin_menu()
            else:
                self.user_menu()

    def admin_menu(self):
        while True:
            print_menu("管理员菜单", [
                "1. 添加图书",
                "2. 删除图书",
                "3. 修改图书信息",
                "4. 查看所有图书",
                "5. 查看所有用户",
                "6. 添加用户",
                "7. 删除用户",
                "8. 退出登录",
                "9. 退出系统"
            ])
            
            choice = input("请选择操作: ")
            
            if choice == "1":
                self.add_book()
            elif choice == "2":
                self.delete_book()
            elif choice == "3":
                self.modify_book()
            elif choice == "4":
                self.list_all_books()
            elif choice == "5":
                self.list_all_users()
            elif choice == "6":
                self.add_user()
            elif choice == "7":
                self.delete_user()
            elif choice == "8":
                self.current_user = None
                break
            elif choice == "9":
                print("感谢使用，再见！")
                exit()
            else:
                print("无效的选择，请重试！")

    def user_menu(self):
        while True:
            print_menu("用户菜单", [
                "1. 查看所有图书",
                "2. 搜索图书",
                "3. 借阅图书",
                "4. 归还图书",
                "5. 查看我的借阅记录",
                "6. 退出登录",
                "7. 退出系统"
            ])
            
            choice = input("请选择操作: ")
            
            if choice == "1":
                self.list_all_books()
            elif choice == "2":
                self.search_books()
            elif choice == "3":
                self.borrow_book()
            elif choice == "4":
                self.return_book()
            elif choice == "5":
                self.view_borrow_history()
            elif choice == "6":
                self.current_user = None
                break
            elif choice == "7":
                print("感谢使用，再见！")
                exit()
            else:
                print("无效的选择，请重试！")

    def add_book(self):
        clear_screen()
        print("=== 添加图书 ===")
        title = input("请输入图书标题: ")
        author = input("请输入作者: ")
        isbn = input("请输入ISBN: ")
        quantity = int(input("请输入数量: "))
        
        book = Book(title, author, isbn, quantity)
        self.db.add_book(book)
        print("图书添加成功！")

    def delete_book(self):
        clear_screen()
        print("=== 删除图书 ===")
        isbn = input("请输入要删除的图书ISBN: ")
        if self.db.delete_book(isbn):
            print("图书删除成功！")
        else:
            print("图书不存在！")

    def modify_book(self):
        clear_screen()
        print("=== 修改图书信息 ===")
        isbn = input("请输入要修改的图书ISBN: ")
        book = self.db.get_book(isbn)
        if not book:
            print("图书不存在！")
            return
        
        print("当前图书信息：")
        print(f"标题: {book.title}")
        print(f"作者: {book.author}")
        print(f"ISBN: {book.isbn}")
        print(f"数量: {book.quantity}")
        
        title = input("请输入新的标题(直接回车保持不变): ")
        author = input("请输入新的作者(直接回车保持不变): ")
        quantity = input("请输入新的数量(直接回车保持不变): ")
        
        if title:
            book.title = title
        if author:
            book.author = author
        if quantity:
            book.quantity = int(quantity)
        
        self.db.update_book(book)
        print("图书信息修改成功！")

    def list_all_books(self):
        clear_screen()
        print("=== 所有图书 ===")
        books = self.db.get_all_books()
        if not books:
            print("暂无图书！")
            return
        
        for book in books:
            print(f"标题: {book.title}")
            print(f"作者: {book.author}")
            print(f"ISBN: {book.isbn}")
            print(f"数量: {book.quantity}")
            print("-" * 30)
        
        input("按回车键继续...")

    def list_all_users(self):
        clear_screen()
        print("=== 所有用户 ===")
        users = self.db.get_all_users()
        if not users:
            print("暂无用户！")
            return
        
        for user in users:
            print(f"用户名: {user.username}")
            print(f"类型: {'管理员' if isinstance(user, Admin) else '普通用户'}")
            print("-" * 30)
        
        input("按回车键继续...")

    def add_user(self):
        clear_screen()
        print("=== 添加用户 ===")
        username = input("请输入用户名: ")
        password = input("请输入密码: ")
        is_admin = input("是否为管理员？(y/n): ").lower() == 'y'
        
        if is_admin:
            user = Admin(username, password)
        else:
            user = User(username, password)
        
        self.db.add_user(user)
        print("用户添加成功！")

    def delete_user(self):
        clear_screen()
        print("=== 删除用户 ===")
        username = input("请输入要删除的用户名: ")
        if self.db.delete_user(username):
            print("用户删除成功！")
        else:
            print("用户不存在！")

    def search_books(self):
        clear_screen()
        print("=== 搜索图书 ===")
        keyword = input("请输入搜索关键词: ")
        books = self.db.search_books(keyword)
        
        if not books:
            print("未找到相关图书！")
            return
        
        for book in books:
            print(f"标题: {book.title}")
            print(f"作者: {book.author}")
            print(f"ISBN: {book.isbn}")
            print(f"数量: {book.quantity}")
            print("-" * 30)
        
        input("按回车键继续...")

    def borrow_book(self):
        clear_screen()
        print("=== 借阅图书 ===")
        isbn = input("请输入要借阅的图书ISBN: ")
        if self.db.borrow_book(self.current_user, isbn):
            print("借阅成功！")
        else:
            print("借阅失败，图书可能不存在或已无库存！")

    def return_book(self):
        clear_screen()
        print("=== 归还图书 ===")
        isbn = input("请输入要归还的图书ISBN: ")
        if self.db.return_book(self.current_user, isbn):
            print("归还成功！")
        else:
            print("归还失败，您可能没有借阅该图书！")

    def view_borrow_history(self):
        clear_screen()
        print("=== 我的借阅记录 ===")
        history = self.db.get_borrow_history(self.current_user)
        if not history:
            print("暂无借阅记录！")
            return
        
        for record in history:
            print(f"图书: {record['book'].title}")
            print(f"借阅时间: {record['borrow_time']}")
            print(f"归还时间: {record['return_time'] or '未归还'}")
            print("-" * 30)
        
        input("按回车键继续...")

if __name__ == "__main__":
    system = LibrarySystem()
    system.run() 